program buildflist;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  md5,
  StrUtils,
  Classes;

var
  i: Integer;
  selectedFiles, slFlist, slIgnoreFiles: TStringList;

procedure SelectFiles_r(const dir: string);
var
  searchRec: TSearchRec;
begin
  if FindFirst(dir + '\*.*', faAnyFile, SearchRec)=0 then
  begin
     repeat
       if (searchRec.Attr=faDirectory) or (searchrec.Attr=fmShareDenyRead) then
       begin
         if (searchRec.Name<>'.') and (searchRec.Name<>'..') then
         begin
          if AnsiEndsText('\', dir) then
            SelectFiles_r(dir + searchRec.Name)
          else
           SelectFiles_r(dir + '\' + searchRec.Name);
         end;
       end else
       begin
          if slIgnoreFiles.IndexOf(searchRec.Name)=-1 then
          begin
            if AnsiEndsText('\', dir) then
              selectedFiles.Add(dir + searchRec.Name)
            else
              selectedFiles.Add(dir + '\' + searchRec.Name);
          end;
       end;
     until FindNext(searchRec)<>0;
     FindClose(searchRec);
  end;
end;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    if ParamCount>0 then
    begin
      selectedFiles := TStringList.Create;
      slIgnoreFiles := TStringList.Create;
      slIgnoreFiles.CaseSensitive := False;
      slFlist := TStringList.Create;
      if FileExists(ExtractFilePath(ParamStr(0)) + 'IgnoreFiles.txt') then
      begin
        WriteLn('load IgnoreFiles.txt');
        slIgnoreFiles.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'IgnoreFiles.txt');
      end;

      SelectFiles_r(ParamStr(1));
      for i := 0 to selectedFiles.Count - 1 do
      begin
        slFlist.Add(
          Md5Print(MD5File(selectedFiles[i])) + #9 +
          StringReplace(selectedFiles[i], ParamStr(1), '', [rfReplaceAll]));
      end;
      slFlist.SaveToFile(ParamStr(1) + 'flist.txt');
      slFlist.Free;
      slIgnoreFiles.Free;
      selectedFiles.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
